package com.Xht.www.dao;

import com.Xht.www.po.UserInfoPO;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class UserInfoDAO extends BaseDAO {

    // 插入用户信息
    public boolean insertUser(UserInfoPO user) {
        if (!isUserInfoValid(user) || isUsernameExists(user.getUsername())) {
            System.out.println("Insert failed: User info is invalid or username already exists. Username: " + user.getUsername());
            System.out.println("Parameters: " +
                    user.getUsername() + ", " + user.getPassword() + ", " +
                    user.getGender() + ", " + user.getAge() + ", " +
                    user.getBirthday() + ", " + user.getUserStatus());

            return false;
        }
        // 自动设置用户状态为“正常”
        user.setUserStatus("正常");
        String sql = "INSERT INTO user_info (username, password, gender, age, birthday, user_status) VALUES (?,?,?,?,?,?)";
        Connection connection = getConnection();
        try (PreparedStatement pstmt = connection.prepareStatement(sql)) {
            pstmt.setString(1, user.getUsername());
            pstmt.setString(2, user.getPassword());
            pstmt.setString(3, user.getGender());
            // 检查 age 是否为 null
            if (user.getAge() != null) {
                pstmt.setInt(4, user.getAge());
            } else {
                pstmt.setNull(4, java.sql.Types.INTEGER);
            }

            pstmt.setDate(5, user.getBirthday());
            pstmt.setString(6, user.getUserStatus());

            System.out.println("Executing SQL: " + sql);
            System.out.println("Parameters: " +
                    user.getUsername() + ", " + user.getPassword() + ", " +
                    user.getGender() + ", " + user.getAge() + ", " +
                    user.getBirthday() + ", " + user.getUserStatus());

            int rows = pstmt.executeUpdate();
            return rows > 0;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        } finally {
            releaseConnection(connection);
        }
    }

    // 检查用户名是否已存在
    private boolean isUsernameExists(String username) {
        String sql = "SELECT COUNT(*) FROM user_info WHERE username = ?";
        Connection connection = getConnection();
        try (PreparedStatement pstmt = connection.prepareStatement(sql)) {
            pstmt.setString(1, username);
            try (ResultSet rs = pstmt.executeQuery()) {
                if (rs.next()) {
                    return rs.getInt(1) > 0;
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            releaseConnection(connection);
        }
        return false;
    }

    // 删除用户信息
    public boolean deleteUser(int userId) {
        String sql = "DELETE FROM user_info WHERE user_id = ?";
        Connection connection = getConnection();
        try (PreparedStatement pstmt = connection.prepareStatement(sql)) {
            pstmt.setInt(1, userId);
            int rows = pstmt.executeUpdate();
            return rows > 0;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        } finally {
            releaseConnection(connection);
        }
    }

    // 查询所有用户信息
    public List<UserInfoPO> getAllUsers() {
        List<UserInfoPO> users = new ArrayList<>();
        String sql = "SELECT * FROM user_info";
        Connection connection = getConnection();
        try (Statement stmt = connection.createStatement();
             ResultSet rs = stmt.executeQuery(sql)) {
            while (rs.next()) {
                UserInfoPO user = new UserInfoPO();
                user.setUserId(rs.getInt("user_id"));
                user.setUsername(rs.getString("username"));
                user.setPassword(rs.getString("password"));
                user.setGender(rs.getString("gender"));
                user.setAge(rs.getInt("age"));
                user.setBirthday(rs.getDate("birthday"));
                user.setUserStatus(rs.getString("user_status"));
                users.add(user);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            releaseConnection(connection);
        }
        return users;
    }

    // 根据用户 ID 查询用户信息
    public UserInfoPO getUserById(int userId) {
        String sql = "SELECT * FROM user_info WHERE user_id = ?";
        Connection connection = getConnection();
        try (PreparedStatement pstmt = connection.prepareStatement(sql)) {
            pstmt.setInt(1, userId);
            try (ResultSet rs = pstmt.executeQuery()) {
                if (rs.next()) {
                    UserInfoPO user = new UserInfoPO();
                    user.setUserId(rs.getInt("user_id"));
                    user.setUsername(rs.getString("username"));
                    user.setPassword(rs.getString("password"));
                    user.setGender(rs.getString("gender"));
                    user.setAge(rs.getInt("age"));
                    user.setBirthday(rs.getDate("birthday"));
                    user.setUserStatus(rs.getString("user_status"));
                    return user;
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            releaseConnection(connection);
        }
        return null;
    }

    // 更新用户信息
    public boolean updateUser(UserInfoPO user) {
        if (!isUserInfoValid(user)) {
            return false;
        }
        String sql = "UPDATE user_info SET username = ?, password = ?, gender = ?, age = ?, birthday = ?, user_status = ? WHERE user_id = ?";
        Connection connection = getConnection();
        try (PreparedStatement pstmt = connection.prepareStatement(sql)) {
            pstmt.setString(1, user.getUsername());
            pstmt.setString(2, user.getPassword());
            pstmt.setString(3, user.getGender());
            pstmt.setInt(4, user.getAge());
            pstmt.setDate(5, user.getBirthday());
            pstmt.setString(6, user.getUserStatus());
            pstmt.setInt(7, user.getUserId());
            int rows = pstmt.executeUpdate();
            return rows > 0;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        } finally {
            releaseConnection(connection);
        }
    }

    // 检验用户信息是否合法
    private boolean isUserInfoValid(UserInfoPO user) {
        if (user.getUsername() == null || user.getUsername().isEmpty()) {
            return false;
        }
        if (user.getPassword() == null || user.getPassword().isEmpty()) {
            return false;
        }
        if (user.getGender() == null || (!user.getGender().equals("男") && !user.getGender().equals("女"))) {
            return false;
        }

        return user.getBirthday() != null;
    }

    // 根据用户名查询用户
    public UserInfoPO getUserByUsername(String username) {
        String sql = "SELECT * FROM user_info WHERE username = ?";
        Connection connection = getConnection();
        try (PreparedStatement pstmt = connection.prepareStatement(sql)) {
            pstmt.setString(1, username);
            try (ResultSet rs = pstmt.executeQuery()) {
                if (rs.next()) {
                    UserInfoPO user = new UserInfoPO();
                    user.setUserId(rs.getInt("user_id"));
                    user.setUsername(rs.getString("username"));
                    user.setPassword(rs.getString("password"));
                    user.setGender(rs.getString("gender"));
                    user.setAge(rs.getInt("age"));
                    user.setBirthday(rs.getDate("birthday"));
                    user.setUserStatus(rs.getString("user_status"));
                    return user;
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            releaseConnection(connection);
        }
        return null;
    }

    // 更新用户状态为解封中
    public boolean updateUserStatusToUnblocking(String username) {
        String sql = "UPDATE user_info SET user_status = '解封中' WHERE username = ?";
        Connection connection = getConnection();
        try (PreparedStatement pstmt = connection.prepareStatement(sql)) {
            pstmt.setString(1, username);
            int rows = pstmt.executeUpdate();
            return rows > 0;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        } finally {
            releaseConnection(connection);
        }
    }

    // 更新用户状态为黑户（封禁）
    public boolean updateUserStatusToBanned(String username) {
        String sql = "UPDATE user_info SET user_status = '黑户' WHERE username = ?";
        Connection connection = getConnection();
        try (PreparedStatement pstmt = connection.prepareStatement(sql)) {
            pstmt.setString(1, username);
            int rows = pstmt.executeUpdate();
            return rows > 0;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        } finally {
            releaseConnection(connection);
        }
    }

    // 更新用户状态为正常（解封）
    public boolean updateUserStatusToNormal(String username) {
        String sql = "UPDATE user_info SET user_status = '正常' WHERE username = ?";
        Connection connection = getConnection();
        try (PreparedStatement pstmt = connection.prepareStatement(sql)) {
            pstmt.setString(1, username);
            int rows = pstmt.executeUpdate();
            return rows > 0;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        } finally {
            releaseConnection(connection);
        }
    }

}